const mysql = require('mysql');
const connection = mysql.createConnection({
    host : '127.0.0.1',
    port : 3306,
    user : 'root',
    password : 'root',
    database : 'albx'
});
module.exports = {
    getAllCategories(callback){
        let sql = 'SELECT * FROM categories';
        connection.query(sql,(err,result)=>{
            callback(err,result);
        });
    },

    addNewCategories(data,callback){
        let sql =  `INSERT INTO categories SET \`NAME\`='${data.name}',slug='${data.slug}',classname='${data.classname}'`;
        connection.query(sql,(err,result)=>{
            callback(err,result);
        });
    },

    getCategoryById(id,callback){
        let sql = `SELECT * FROM categories WHERE id = ${id}` 
        connection.query(sql,(err,result)=>{
            callback(err,result[0]);
        });
    },

    deleteCategoryById(id,callback){
        let sql = `DELETE FROM categories WHERE id = ${id}`;
        connection.query(sql,(err,result)=>{
            callback(err,result);
        });
    },

    editCategoryById(id,data,callback) {
        //?的使用方式是mysql这个第三方模块里面提供的语法，其中一个功能就是可以快速的书写键值对
        // ?的原理就是快速书写了以下代码拼接在了一起
        // let str = connection.format(sql,data);
        // console.log(str);
        let sql = `update categories set ? where id=${id}`;
        connection.query(sql,data,(err,result)=>{
            callback(err,result);
        });
    },

    deleteMultple(ids,callback){
        // 将数组中的元素以逗号为间隔拼接成一个字符串
        let data = ids.join();
        let sql = `DELETE FROM categories WHERE id in (${data})`;
        connection.query(sql,(err,result)=>{
            callback(err,result);
        });
    }

}